home *** CD-ROM | disk | FTP | other *** search
/ Disc to the Future 2 / Disc to the Future Part II Programmer's Reference (Wayzata Technology)(6013)(1992).bin / MAC / THINKC / 3_0 / LZARI__ / LZARI.C
Text File  |  1989-07-11  |  13KB  |  493 lines

  1. /**************************************************************
  2.     LZARI.C -- A Data Compression Program
  3.     (tab = 4 spaces)
  4. ***************************************************************
  5.     4/7/1989 Haruhiko Okumura
  6.     Use, distribute, and modify this program freely.
  7.     Please send me your improved versions.
  8.         PC-VAN        SCIENCE
  9.         NIFTY-Serve    PAF01022
  10.         CompuServe    74050,1022
  11. **************************************************************/
  12. #include <stdio.h>
  13. /*#include <stdlib.h>*/
  14. #include <strings.h>
  15. #include <ctype.h>
  16.  
  17. /********** Bit I/O **********/
  18.  
  19. FILE  *infile, *outfile;
  20. unsigned long int  textsize = 0, codesize = 0, printcount = 0;
  21.  
  22. void Error(message)
  23. char *message;
  24. {
  25.     printf("\n%s\n", message);
  26.     exit(1);
  27. }
  28.  
  29. void PutBit(bit)  /* Output one bit (bit = 0,1) */
  30. register int bit;
  31. {
  32.     static unsigned int  buffer = 0, mask = 128;
  33.     
  34.     if (bit) buffer |= mask;
  35.     if ((mask >>= 1) == 0) {
  36.         if (putc(buffer, outfile) == EOF) Error("Write Error");
  37.         buffer = 0;  mask = 128;  codesize++;
  38.     }
  39. }
  40.  
  41. void FlushBitBuffer()  /* Send remaining bits */
  42. {
  43.     register int  i;
  44.     
  45.     for (i = 0; i < 7; i++) PutBit(0);
  46. }
  47.  
  48. int GetBit()  /* Get one bit (0 or 1) */
  49. {
  50.     static unsigned int  buffer, mask = 0;
  51.     
  52.     if ((mask >>= 1) == 0) {
  53.         buffer = getc(infile);  mask = 128;
  54.     }
  55.     return ((buffer & mask) != 0);
  56. }
  57.  
  58. /********** LZSS with multiple binary trees **********/
  59.  
  60. #define N         4096    /* size of ring buffer */
  61. #define F           65    /* was 60 upper limit for match_length */
  62. #define THRESHOLD    2   /* encode string into position and length
  63.                            if match_length is greater than this */
  64. #define NIL            N    /* index for root of binary search trees */
  65.  
  66. unsigned char  text_buf[N + F - 1];    /* ring buffer of size N,
  67.             with extra F-1 bytes to facilitate string comparison */
  68. int        match_position, match_length,  /* of longest match.  These are
  69.             set by the InsertNode() procedure. */
  70.         lson[N + 1], rson[N + 257], dad[N + 1];  /* left & right children &
  71.             parents -- These constitute binary search trees. */
  72.  
  73. void InitTree()  /* Initialize trees */
  74. {
  75.     register int  i;
  76.  
  77.     /* For i = 0 to N - 1, rson[i] and lson[i] will be the right and
  78.        left children of node i.  These nodes need not be initialized.
  79.        Also, dad[i] is the parent of node i.  These are initialized to
  80.        NIL (= N), which stands for 'not used.'
  81.        For i = 0 to 255, rson[N + i + 1] is the root of the tree
  82.        for strings that begin with character i.  These are initialized
  83.        to NIL.  Note there are 256 trees. */
  84.  
  85.     for (i = N + 1; i <= N + 256; i++) rson[i] = NIL;    /* root */
  86.     for (i = 0; i < N; i++) dad[i] = NIL;    /* node */
  87. }
  88.  
  89. void InsertNode(r)
  90. register int r;
  91.     /* Inserts string of length F, text_buf[r..r+F-1], into one of the
  92.        trees (text_buf[r]'th tree) and returns the longest-match position
  93.        and length via the global variables match_position and match_length.
  94.        If match_length = F, then removes the old node in favor of the new
  95.        one, because the old one will be deleted sooner.
  96.        Note r plays double role, as tree node and position in buffer. */
  97. {
  98.     register int  i, p, cmp, temp;
  99.     register unsigned char  *key;
  100.  
  101.     cmp = 1;  key = &text_buf[r];  p = N + 1 + key[0];
  102.     rson[r] = lson[r] = NIL;  match_length = 0;
  103.     for ( ; ; ) {
  104.         if (cmp >= 0) {
  105.             if (rson[p] != NIL) p = rson[p];
  106.             else {  rson[p] = r;  dad[r] = p;  return;  }
  107.         } else {
  108.             if (lson[p] != NIL) p = lson[p];
  109.             else {  lson[p] = r;  dad[r] = p;  return;  }
  110.         }
  111.         for (i = 1; i < F; i++)
  112.             if ((cmp = key[i] - text_buf[p + i]) != 0)  break;
  113.         if (i > THRESHOLD) {
  114.             if (i > match_length) {
  115.                 match_position = (r - p) & (N - 1);
  116.                 if ((match_length = i) >= F) break;
  117.             } else if (i == match_length) {
  118.                 if ((temp = (r - p) & (N - 1)) < match_position)
  119.                     match_position = temp;
  120.             }
  121.         }
  122.     }
  123.     dad[r] = dad[p];  lson[r] = lson[p];  rson[r] = rson[p];
  124.     dad[lson[p]] = r;  dad[rson[p]] = r;
  125.     if (rson[dad[p]] == p) rson[dad[p]] = r;
  126.     else                   lson[dad[p]] = r;
  127.     dad[p] = NIL;  /* remove p */
  128. }
  129.  
  130. void DeleteNode(p)  /* Delete node p from tree */
  131. register int p;
  132. {
  133.     register int  q;
  134.     
  135.     if (dad[p] == NIL) return;  /* not in tree */
  136.     if (rson[p] == NIL) q = lson[p];
  137.     else if (lson[p] == NIL) q = rson[p];
  138.     else {
  139.         q = lson[p];
  140.         if (rson[q] != NIL) {
  141.             do {  q = rson[q];  } while (rson[q] != NIL);
  142.             rson[dad[q]] = lson[q];  dad[lson[q]] = dad[q];
  143.             lson[q] = lson[p];  dad[lson[p]] = q;
  144.         }
  145.         rson[q] = rson[p];  dad[rson[p]] = q;
  146.     }
  147.     dad[q] = dad[p];
  148.     if (rson[dad[p]] == p) rson[dad[p]] = q;
  149.     else                   lson[dad[p]] = q;
  150.     dad[p] = NIL;
  151. }
  152.  
  153. /********** Arithmetic Compression **********/
  154.  
  155. /*  If you are not familiar with arithmetic compression, you should read
  156.         I. E. Witten, R. M. Neal, and J. G. Cleary,
  157.             Communications of the ACM, Vol. 30, pp. 520-540 (1987),
  158.     from which much have been borrowed.  */
  159.  
  160. #define M   15
  161.  
  162. /*    Q1 (= 2 to the M) must be sufficiently large, but not so
  163.     large as the unsigned long 4 * Q1 * (Q1 - 1) overflows.  */
  164.  
  165. #define Q1  (1L << M)
  166. #define Q2  (2 * Q1)
  167. #define Q3  (3 * Q1)
  168. #define Q4  (4 * Q1)
  169. #define MAX_CUM (Q1 - 1)
  170.  
  171. #define N_CHAR  (256 - THRESHOLD + F)
  172.     /* character code = 0, 1, ..., N_CHAR - 1 */
  173.  
  174. unsigned long int  low = 0;
  175. unsigned long int high = Q4;
  176.  
  177. unsigned long int value = 0;
  178. int  shifts = 0;  /* counts for magnifying low and high around Q2 */
  179. /*
  180. int  char_to_sym[N_CHAR], sym_to_char[N_CHAR + 1];
  181.  
  182. unsigned int
  183.     sym_freq[N_CHAR + 1],  /* frequency for symbols *
  184.     sym_cum[N_CHAR + 1],   /* cumulative freq for symbols *
  185.     position_cum[N + 1];   /* cumulative freq for positions *
  186.  */
  187.  
  188. int *char_to_sym, *sym_to_char;
  189. unsigned int *sym_freq, *sym_cum, *position_cum;
  190.  
  191.  
  192. void StartModel()  /* Initialize model */
  193. {
  194.     register int ch, sym, i;
  195.     
  196.     /* Mac 32K workaround */
  197.     char_to_sym = (int *) NewPtr(sizeof(int) * (N_CHAR));
  198.     sym_to_char = (int *) NewPtr(sizeof(int) * (N_CHAR));
  199.     sym_freq = (unsigned int *) NewPtr(sizeof(unsigned int) * (N_CHAR+1));
  200.     sym_cum = (unsigned int *) NewPtr(sizeof(unsigned int) * (N_CHAR+1));
  201.     position_cum = (unsigned int *) NewPtr(sizeof(unsigned int) * (N+1));
  202.     
  203.     sym_cum[N_CHAR] = 0;
  204.     for (sym = N_CHAR; sym >= 1; sym--) {
  205.         ch = sym - 1;
  206.         char_to_sym[ch] = sym;  sym_to_char[sym] = ch;
  207.         sym_freq[sym] = 1;
  208.         sym_cum[sym - 1] = sym_cum[sym] + sym_freq[sym];
  209.     }
  210.     sym_freq[0] = 0;  /* sentinel (!= sym_freq[1]) */
  211.     position_cum[N] = 0;
  212.     for (i = N; i >= 1; i--)
  213.         position_cum[i - 1] = position_cum[i] + 10000 / (i + 200);
  214.             /* empirical distribution function (quite tentative) */
  215.             /* Please devise a better mechanism! */
  216. }
  217.  
  218. void UpdateModel(sym)
  219. register int sym;
  220. {
  221.     int i, c, ch_i, ch_sym;
  222.     
  223.     if (sym_cum[0] >= MAX_CUM) {
  224.         c = 0;
  225.         for (i = N_CHAR; i > 0; i--) {
  226.             sym_cum[i] = c;
  227.             c += (sym_freq[i] = (sym_freq[i] + 1) >> 1);
  228.         }
  229.         sym_cum[0] = c;
  230.     }
  231.     for (i = sym; sym_freq[i] == sym_freq[i - 1]; i--) ;
  232.     if (i < sym) {
  233.         ch_i = sym_to_char[i];    ch_sym = sym_to_char[sym];
  234.         sym_to_char[i] = ch_sym;  sym_to_char[sym] = ch_i;
  235.         char_to_sym[ch_i] = sym;  char_to_sym[ch_sym] = i;
  236.     }
  237.     sym_freq[i]++;
  238.     while (--i >= 0) sym_cum[i]++;
  239. }
  240.  
  241. static void Output(bit)  /* Output 1 bit, followed by its complements */
  242. register int bit;
  243. {
  244.     PutBit(bit);
  245.     for ( ; shifts > 0; shifts--) PutBit(! bit);
  246. }
  247.  
  248. void EncodeChar(ch)
  249. register int ch;
  250. {
  251.     register int  sym;
  252.     register unsigned long int  range;
  253.  
  254.     sym = char_to_sym[ch];
  255.     range = high - low;
  256.     high = low + (range * sym_cum[sym - 1]) / sym_cum[0];
  257.     low +=       (range * sym_cum[sym    ]) / sym_cum[0];
  258.     for ( ; ; ) {
  259.         if (high <= Q2) Output(0);
  260.         else if (low >= Q2) {
  261.             Output(1);  low -= Q2;  high -= Q2;
  262.         } else if (low >= Q1 && high <= Q3) {
  263.             shifts++;  low -= Q1;  high -= Q1;
  264.         } else break;
  265.         low += low;  high += high;
  266.     }
  267.     UpdateModel(sym);
  268. }
  269.  
  270. void EncodePosition(position)
  271. register int position;
  272. {
  273.     register unsigned long int  range;
  274.  
  275.     range = high - low;
  276.     high = low + (range * position_cum[position    ]) / position_cum[0];
  277.     low +=       (range * position_cum[position + 1]) / position_cum[0];
  278.     for ( ; ; ) {
  279.         if (high <= Q2) Output(0);
  280.         else if (low >= Q2) {
  281.             Output(1);  low -= Q2;  high -= Q2;
  282.         } else if (low >= Q1 && high <= Q3) {
  283.             shifts++;  low -= Q1;  high -= Q1;
  284.         } else break;
  285.         low += low;  high += high;
  286.     }
  287. }
  288.  
  289. void EncodeEnd()
  290. {
  291.     shifts++;
  292.     if (low < Q1) Output(0);  else Output(1);
  293.     FlushBitBuffer();  /* flush bits remaining in buffer */
  294. }
  295.  
  296. int BinarySearchSym(x)
  297. register unsigned int x;
  298.     /* 1      if x >= sym_cum[1],
  299.        N_CHAR if sym_cum[N_CHAR] > x,
  300.        i such that sym_cum[i - 1] > x >= sym_cum[i] otherwise */
  301. {
  302.     register int i, j, k;
  303.     
  304.     i = 1;  j = N_CHAR;
  305.     while (i < j) {
  306.         k = (i + j) / 2;
  307.         if (sym_cum[k] > x) i = k + 1;  else j = k;
  308.     }
  309.     return i;
  310. }
  311.  
  312. int BinarySearchPos(x)
  313. register unsigned int x;
  314.     /* 0 if x >= position_cum[1],
  315.        N - 1 if position_cum[N] > x,
  316.        i such that position_cum[i] > x >= position_cum[i + 1] otherwise */
  317. {
  318.     register int i, j, k;
  319.     
  320.     i = 1;  j = N;
  321.     while (i < j) {
  322.         k = (i + j) / 2;
  323.         if (position_cum[k] > x) i = k + 1;  else j = k;
  324.     }
  325.     return i - 1;
  326. }
  327.  
  328. void StartDecode()
  329. {
  330.     int i;
  331.  
  332.     for (i = 0; i < M + 2; i++)
  333.         value = 2 * value + GetBit();
  334. }
  335.  
  336. int DecodeChar()
  337. {
  338.     register int     sym, ch;
  339.     register unsigned long int  range;
  340.     
  341.     range = high - low;
  342.     sym = BinarySearchSym((unsigned int)
  343.         (((value - low + 1) * sym_cum[0] - 1) / range));
  344.     high = low + (range * sym_cum[sym - 1]) / sym_cum[0];
  345.     low +=       (range * sym_cum[sym    ]) / sym_cum[0];
  346.     for ( ; ; ) {
  347.         if (low >= Q2) {
  348.             value -= Q2;  low -= Q2;  high -= Q2;
  349.         } else if (low >= Q1 && high <= Q3) {
  350.             value -= Q1;  low -= Q1;  high -= Q1;
  351.         } else if (high > Q2) break;
  352.         low += low;  high += high;
  353.         value = 2 * value + GetBit();
  354.     }
  355.     ch = sym_to_char[sym];
  356.     UpdateModel(sym);
  357.     return ch;
  358. }
  359.  
  360. int DecodePosition()
  361. {
  362.     register int position;
  363.     register unsigned long int  range;
  364.     
  365.     range = high - low;
  366.     position = BinarySearchPos((unsigned int)
  367.         (((value - low + 1) * position_cum[0] - 1) / range));
  368.     high = low + (range * position_cum[position    ]) / position_cum[0];
  369.     low +=       (range * position_cum[position + 1]) / position_cum[0];
  370.     for ( ; ; ) {
  371.         if (low >= Q2) {
  372.             value -= Q2;  low -= Q2;  high -= Q2;
  373.         } else if (low >= Q1 && high <= Q3) {
  374.             value -= Q1;  low -= Q1;  high -= Q1;
  375.         } else if (high > Q2) break;
  376.         low += low;  high += high;
  377.         value = 2 * value + GetBit();
  378.     }
  379.     return position;
  380. }
  381.  
  382. #define SEEK_END 2
  383. #define SEEK_CUR 1
  384. #define SEEK_SET 0
  385. /********** Encode and Decode **********/
  386.  
  387. void Encode()
  388. {
  389.     register int  i, c, len, r, s, last_match_length;
  390.     
  391.     fseek(infile, 0L, SEEK_END);
  392.     textsize = ftell(infile);
  393.     if (fwrite(&textsize, sizeof textsize, 1, outfile) < 1)
  394.         Error("Write Error");  /* output size of text */
  395.     codesize += sizeof textsize;
  396.     if (textsize == 0) return;
  397.     rewind(infile);  textsize = 0;
  398.     StartModel();  InitTree();
  399.     s = 0;  r = N - F;
  400.     for (i = s; i < r; i++) text_buf[i] = ' ';
  401.     for (len = 0; len < F && (c = getc(infile)) != EOF; len++)
  402.         text_buf[r + len] = c;
  403.     textsize = len;
  404.     for (i = 1; i <= F; i++) InsertNode(r - i);
  405.     InsertNode(r);
  406.     do {
  407.         if (match_length > len) match_length = len;
  408.         if (match_length <= THRESHOLD) {
  409.             match_length = 1;  EncodeChar(text_buf[r]);
  410.         } else {
  411.             EncodeChar(255 - THRESHOLD + match_length);
  412.             EncodePosition(match_position - 1);
  413.         }
  414.         last_match_length = match_length;
  415.         for (i = 0; i < last_match_length &&
  416.                 (c = getc(infile)) != EOF; i++) {
  417.             DeleteNode(s);  text_buf[s] = c;
  418.             if (s < F - 1) text_buf[s + N] = c;
  419.             s = (s + 1) & (N - 1);
  420.             r = (r + 1) & (N - 1);
  421.             InsertNode(r);
  422.         }
  423.         if ((textsize += i) > printcount) {
  424.             printf("%12ld\r", textsize);  printcount += 1024;
  425.         }
  426.         while (i++ < last_match_length) {
  427.             DeleteNode(s);
  428.             s = (s + 1) & (N - 1);
  429.             r = (r + 1) & (N - 1);
  430.             if (--len) InsertNode(r);
  431.         }
  432.     } while (len > 0);
  433.     EncodeEnd();
  434.     printf("In : %lu bytes\n", textsize);
  435.     printf("Out: %lu bytes\n", codesize);
  436.     printf("Out/In: %.3f\n", (double)codesize / textsize);
  437. }
  438.  
  439. void Decode()
  440. {
  441.     register int  i, j, k, r, c;
  442.     register unsigned long int  count;
  443.  
  444.     if (fread(&textsize, sizeof textsize, 1, infile) < 1)
  445.         Error("Read Error");  /* read size of text */
  446.     if (textsize == 0) return;
  447.     StartDecode();  StartModel();
  448.     for (i = 0; i < N - F; i++) text_buf[i] = ' ';
  449.     r = N - F;
  450.     for (count = 0; count < textsize; ) {
  451.         c = DecodeChar();
  452.         if (c < 256) {
  453.             putc(c, outfile);  text_buf[r++] = c;
  454.             r &= (N - 1);  count++;
  455.         } else {
  456.             i = (r - DecodePosition() - 1) & (N - 1);
  457.             j = c - 255 + THRESHOLD;
  458.             for (k = 0; k < j; k++) {
  459.                 c = text_buf[(i + k) & (N - 1)];
  460.                 putc(c, outfile);  text_buf[r++] = c;
  461.                 r &= (N - 1);  count++;
  462.             }
  463.         }
  464.         if (count > printcount) {
  465.             printf("%12lu\r", count);  printcount += 1024;
  466.         }
  467.     }
  468.     printf("%12lu\n", count);
  469. }
  470.  
  471. #define EXIT_FAILURE 1
  472. #define EXIT_SUCCESS 0
  473. int _main(argc,argv)
  474. int argc;
  475. char **argv;
  476. {
  477.     char  *s;
  478.     
  479.     if (argc != 4) {
  480.         printf("'e file1 file2' encodes file1 into file2.\n"
  481.                "'d file2 file1' decodes file2 into file1.\n");
  482.         return 1;
  483.     }
  484.     if ((s = argv[1], s[1] || strpbrk(s, "DEde") == NULL)
  485.      || (s = argv[2], (infile  = fopen(s, "rb")) == NULL)
  486.      || (s = argv[3], (outfile = fopen(s, "wb")) == NULL)) {
  487.         printf("??? %s\n", s);  return EXIT_FAILURE;
  488.     }
  489.     if (toupper(*argv[1]) == 'E') Encode();  else Decode();
  490.     fclose(infile);  fclose(outfile);
  491.     return 0;
  492. }
  493.